//
//  AppDelegate.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/3/13.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginVC.h"
#import "BaseNavigationController.h"
#import "BaseTabBarController.h"
#import <UMCommon/UMCommon.h>
#import <UMCommon/MobClick.h>
#import "WeiboSDK.h"
#import "MailDetailsVC.h"
#define WeChatKey @"wxa864766b0014b9a7"
#define WeBoKey @"df432e9973e8bed0595efe8450e62698"
#define UMCCommonKey @"5efd8fe6dbc2ec078c814b97"

UserModel *userModel;
@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    

//    //开发者需要显式的调用此函数，日志系统才能工作
//    [UMConfigure setLogEnabled:YES];
    
    [UMConfigure initWithAppkey:UMCCommonKey channel:@"App Store"];
    [WeiboSDK registerApp:WeBoKey];


    //向微信注册
    [WXApi registerApp:WeChatKey universalLink:@"https://api.ofajs.cn/"];

    
    
    
    BaseTabBarController *baseTabBar = [[BaseTabBarController alloc]init];

    self.window.rootViewController = baseTabBar;
    
    
//    if ([[NSUserDefaults standardUserDefaults] boolForKey:kisLogin]) {
//
//        BaseTabBarController *baseTabBar = [[BaseTabBarController alloc]init];
//
//        self.window.rootViewController = baseTabBar;
//
//    }else {
//        LoginVC *vc = [[LoginVC alloc]initWithNibName:@"LoginVC" bundle:nil];
//        BaseNavigationController *navigationController = [[BaseNavigationController alloc] initWithRootViewController:vc];
//
//        self.window.rootViewController = navigationController;
//    }
       
  
    [self.window makeKeyAndVisible];
    
    [self configureSVP];
    
    return YES;
}




- (void)confitUShareSettings
{
    /*
     * 打开图片水印
     */
    //[UMSocialGlobal shareInstance].isUsingWaterMark = YES;

    /*
     * 关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
     <key>NSAppTransportSecurity</key>
     <dict>
     <key>NSAllowsArbitraryLoads</key>
     <true/>
     </dict>
     */
    //[UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;


}


#pragma mark - 全局设置SVP
- (void)configureSVP {
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setMinimumDismissTimeInterval:1.0];
    [IQKeyboardManager sharedManager].enable = YES;
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable restorableObjects))restorationHandler {
    NSURL *url = userActivity.webpageURL;
    NSString * urlStr = [url absoluteString];
    
    if ([urlStr containsString:@"pay"]){ //微信支付的回调
        NSString *result = [url absoluteString];
        NSLog(@"微信------%@",result);
        NSArray *array = [result componentsSeparatedByString:@"="];
        NSString *resultNumber = [array lastObject];
        NSLog(@"微信------%@",resultNumber);
        if ([resultNumber integerValue] == 0){ //成功
            //发送支付成功的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:NoticePaySuccess object:nil];
        }else if ([resultNumber integerValue] == -1) { //错误
            //发送支付失败的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:NoticePayFailure object:nil];
        }else if ([resultNumber integerValue] == -2){ //用户取消
            //发送支付取消的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:NoticePayCancel object:nil];
        }
    }else {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
         }];
        
        return NO;
    }
    
    return [WXApi handleOpenUniversalLink:userActivity delegate:self];
}

//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
//    return  [WXApi handleOpenURL:url delegate:self];
//}
//
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
//    return [WXApi handleOpenURL:url delegate:self];
//}


// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    NSString *urlString = [NSString stringWithFormat:@"%@",url];
    if ([urlString containsString:@"renren://renren:8080/download?code="]) {
         NSString *code = [urlString substringFromIndex:35];
        if (![CommonTTool isStrNull:code]) {
            [CommonTTool setUserDefaults:code key:SHARE_UserCode];
        }
        
    }

    if ([urlString containsString:@"renren://renren:8080/goodDetail?"]) {
        //判断是商品详情 截取指定字符串
        NSString *dataString = [urlString substringFromIndex:32];
        NSArray *dataArray = [dataString componentsSeparatedByString:@"&"];
        NSString *type = @"";
        NSString *sku_id = @"";
        NSString *code = @"";
        NSString *tg_group_id = @"";
        for (int i = 0; i < dataArray.count; i++) {
//            NSString *str = dataArray[i];
            NSRange range = [dataArray[i] rangeOfString:@"="];//匹配得到的下标
            if (i == 0) {
                type = [dataArray[i] substringFromIndex:range.location+1];//截取范围内的字符串
            }
            if (i == 1) {
                sku_id = [dataArray[i] substringFromIndex:range.location+1];//截取范围内的字符串
            }
            
            if (i == 2) {
                code = [dataArray[i] substringFromIndex:range.location+1];//截取范围内的字符串
                if (![CommonTTool isStrNull:code]) {
                    [CommonTTool setUserDefaults:code key:SHARE_UserCode];
                }
            }
            
            if (i == 3) {
                tg_group_id = [dataArray[i] substringFromIndex:range.location+1];//截取范围内的字符串
            }

        }
        
        MailDetailsVC *vc = [[MailDetailsVC alloc] init];
        MailGoodsModel *goodsModel = [[MailGoodsModel alloc]init];
        goodsModel.sku_id = sku_id;
        if ([type isEqual:@"3"]) {
            goodsModel.sku_type = 1;
            goodsModel.is_pt = 2;
            if (![CommonTTool isStrNull:tg_group_id]) {
                //显示拼团信息
                vc.tg_group_id = tg_group_id;
            }
        }else {
            goodsModel.sku_type = [type intValue];
        }
        vc.goodsModel = goodsModel;
        vc.hidesBottomBarWhenPushed = YES;
        [[CommonTTool getCurrentVC].navigationController pushViewController:vc animated:YES];
        
    }
    
    //微信分享回调
    if ([[NSString stringWithFormat:@"%@",url] containsString:@"wechat"]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    
   if ([url.host isEqualToString:@"pay"]){ //微信支付的回调
        NSString *result = [url absoluteString];
        NSLog(@"微信------%@",result);
        NSArray *array = [result componentsSeparatedByString:@"="];
        NSString *resultNumber = [array lastObject];
        NSLog(@"微信------%@",resultNumber);
        if ([resultNumber integerValue] == 0){ //成功
            //发送支付成功的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:NoticePaySuccess object:nil];
        }else if ([resultNumber integerValue] == -1) { //错误
            //发送支付失败的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:NoticePayFailure object:nil];
        }else if ([resultNumber integerValue] == -2){ //用户取消
            //发送支付取消的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:NoticePayCancel object:nil];
        }
    }
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            NSString *resultStatus = [resultDic objectForKey:@"resultStatus"];
               
               if ([resultStatus intValue] == 9000) {
                   //发送支付成功的通知
                   [[NSNotificationCenter defaultCenter] postNotificationName:NoticePaySuccess object:nil];
               }else {
                  //发送支付失败的通知
                  [[NSNotificationCenter defaultCenter] postNotificationName:NoticePayFailure object:nil];
               }
        }];
    }
    
    
    return YES;
}


#pragma mark - UISceneSession lifecycle


//- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
//    // Called when a new scene session is being created.
//    // Use this method to select a configuration to create the new scene with.
//    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
//}
//
//
//- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
//    // Called when the user discards a scene session.
//    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
//    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
//}


-(void) onReq:(BaseReq*)reqonReq {
    
    
}
- (void)onResp:(BaseResp *)resp {
    // 1.分享后回调类
        if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
            if (resp.errCode == 0) {
                //SendMessageToWXResp *resp1 = (SendMessageToWXResp *)resp;
                [[NSNotificationCenter defaultCenter] postNotificationName:kShareSuccess object:nil];
            }else{
                [[NSNotificationCenter defaultCenter] postNotificationName:kShareFailure object:nil];
            }
        }

    
}

    


@end
